<!-- 基础数据创建 -->
<script setup lang="ts">
import type { BasicClassValueField, BasicDataInfo, SaveRequestData } from "@@/apis/basic-data/types"
import type { FormInstance, FormRules } from "element-plus"
import type { VxeTablePropTypes } from "vxe-table"
import { saveStructField, searchStructDataApi } from "@@/apis/basic-data"
import basicDrawer from "@@/components/plugins/DrawerParamAdd.vue"
import SelectTag from "@@/components/SelectTag/index.vue"
import { BSDataTypeEnum, FormTypeEnum, RecordTypeEnum } from "@@/constants/other-keys"
import { ElMessage, ElMessageBox } from "element-plus"
import { cloneDeep } from "lodash"
import { v4 as uuidv4 } from "uuid"
import { computed, onMounted, ref } from "vue"
import { useRoute, useRouter } from "vue-router"
import XEUtils from "xe-utils"
import componentVue from "./components/component.vue"
import EnumDrawer from "./components/DrawerEnum.vue"
import { closeRoute } from "@/common/composables/useCloseRouteListener";
import "@@/components/plugins/EditDownModal"

defineOptions({
  // 命名当前组件
  name: "BasicDataCreate"
})

const router = useRouter()
const route = useRoute()

const basicData = ref<BasicDataInfo>({
  id: undefined,
  name: "",
  code: "",
  tag: "",
  parentId: "",
  description: "",
  separator: ",",
  type: route.query.type as BSDataTypeEnum
})
const detailData = ref({
  name: "",
  code: "",
  type: route.query.type as BSDataTypeEnum,
  typeId: 0,
  separator: "",
  recordType: "",
  typeCode: ""
})
const rules = ref<FormRules>({
  code: [
    { required: true, message: '请输入', trigger: "blur" },
    { message: "第一个字符必须是字母（大小写均可）或下划线 _", pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/, trigger: "blur" }
  ],
  name: [{ required: true, message: "请输入", trigger: "blur" }],
  separator: [{ required: true, message: "请输入", trigger: "blur" }]
})
const activeTab = ref("table")
const tableData = ref<FormData[]>([])
const listObj = ref({}) // 列表的数据
const componentRef = ref<FormInstance | null>(null)
const parentOptions = ref<{ label: string, value: string }[]>([])
const fieldTableRef = ref()
const editParamValue = ref<FormData>()
const dialogTyle = ref<FormTypeEnum>(FormTypeEnum.CREATE)

// 页面新增的参数信息
interface FormData {
  staticFlag?: number
  [key: string]: any
}
// 页面新增class参数信息
const insertFields = ref<FormData[]>([])
const removeFields = ref<FormData[]>([])

const DEFAULT_ITEM_VALUE: BasicClassValueField = {
  name: undefined,
  code: undefined,
  type: BSDataTypeEnum.Base,
  typeId: undefined,
  typeCode: undefined,
  separator: undefined,
  recordType: RecordTypeEnum.Base,
  staticFlag: 1,
  value: "",
  sort: tableData.value.length + 1
}
const validRules = ref<VxeTablePropTypes.EditRules>({
  code: [
    { required: true, message: '参数名不能为空', trigger: "blur" },
    { message: "第一个字符必须是字母（大小写均可）或下划线 _", pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/, trigger: "blur" }
  ],
  typeCode: [
    { required: true, message: "数据类型必选择" }
  ]
})
const validEnumRules = ref<VxeTablePropTypes.EditRules>({
  code: [{ required: true, message: "枚举值不能为空", trigger: "blur" }]
})

const deleteBtn = computed(() => {
  if (fieldTableRef.value) {
    const selectRecords = fieldTableRef.value.getCheckboxRecords()
    return selectRecords.length > 0
  }
  return false
})

// 新建参数
async function handleCreateTask(record?: BasicClassValueField) {
  if (record == undefined) {
    record = cloneDeep(DEFAULT_ITEM_VALUE)
  }
  record.id = uuidv4()
  tableData.value.push(record)
  insertFields.value.push(record)
  fieldTableRef.value.setEditRow(record, "code")
}
function handleTopCreateTask() {
  dialogTyle.value = FormTypeEnum.CREATE
  dialogVisible.value = true
}
// 批量删除参数
function handleMultipleDelete() {
  if (fieldTableRef.value) {
    const selectRecords = fieldTableRef.value.getCheckboxRecords()
    const ids: string[] = []
    const names: string[] = []
    selectRecords.forEach((item: { id: string, code: string }) => {
      ids.push(item.id as string)
      names.push(item.code as string)
    })
    ElMessageBox.confirm(`正在删除参数：${names.join("，")}，确认删除？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      const delIds: number[] = []
      XEUtils.eachTree(selectRecords, (item) => {
        if (!removeFields.value.some(obj => item.id === obj.id)) {
          delIds.push(item.id)
          removeFields.value.push(item)
        }
      }, { children: "children" })
      tableData.value = tableData.value.filter(item => !delIds.includes(item.id))
    })
  }
}
// 获取组件模型列表
onMounted(() => {
  if (route.query.type == BSDataTypeEnum.Class) {
    searchStructDataApi({
      type: BSDataTypeEnum.Class,
      code: undefined,
      pageSize: undefined,
      current: undefined
    }).then(({ data }) => {
      parentOptions.value = data.rows.filter(item => item.name && item.id)
        .map(item => ({
          label: item.name!,
          value: item.id!
        }))
    })
  }
})

// 保存
// 提交
async function handleSave() {
  if (!componentRef.value) return false
  const valueErrors = await fieldTableRef.value.validate(true)
  if (valueErrors) {
    ElMessage.warning("参数校验未通过")
    return
  }
  componentRef.value.validate().then((valid) => {
    const _tableData = cloneDeep(tableData.value)
    _tableData.forEach((item, index) => {
      item.sort = index + 1
      delete item.id
    })
    const compItem = cloneDeep(basicData.value)
    compItem.tag = JSON.stringify(compItem.tag)
    let saveData: SaveRequestData = {
      basicData: cloneDeep(compItem),
      insertFields: undefined,
      insertEnums: undefined,
      removeFields: undefined,
      removeEnums: undefined,
      updateFields: undefined,
      updateEnums: undefined
    }
    if (basicData.value.type == BSDataTypeEnum.Class) {
      saveData.insertFields = _tableData
      saveData.removeFields = []
      saveData.updateFields = []
    } else {
      saveData.insertEnums = _tableData
      saveData.removeEnums = []
      saveData.updateEnums = []
    }
    saveStructField(saveData).then((res) => {
      ElMessage.success("保存成功")
      handleCancel()
    }).catch(() => {
      ElMessage.error("保存失败")
    })
  }).catch(() => {
    return false
  })
}
// 退出
function handleCancel() {
  closeRoute()
  router.back()
}
const dialogVisible = ref<boolean>(false)

// 弹窗清空数据
function closeDialog() {
  dialogVisible.value = false
}

function handleEditDialog(data: FormData) {
  dialogTyle.value = FormTypeEnum.EDIT
  dialogVisible.value = true
  editParamValue.value = cloneDeep(data)
}

// 保存参数
function handleConfirm(formData: BasicClassValueField) {
  if (formData.id == undefined) {
    // 新增
    handleCreateTask(cloneDeep(formData))
  } else {
    tableData.value.forEach((item) => {
      if (item.id == formData.id) {
        fieldTableRef.value.setRow(item, formData)
      }
    })
  }
  dialogVisible.value = false
}

function removeNode(id: string) {
  tableData.value = tableData.value.filter(item => item.id != undefined && item.id != id)
}
</script>

<template>
  <div class="app-container pager-container">
    <div class="app-container-content">
      <div class="cpi-header">
        <span class="cpi-header-text">基本信息</span>
      </div>
      <div class="basic-data-create-table">
        <el-form ref="componentRef" :model="basicData" status-icon :rules="rules" label-position="right" label-width="100" class="demo-basicData">
          <el-row :gutter="24">
            <el-col :sm="12" :lg="6">
              <el-form-item label="名称" prop="code">
                <el-input v-model="basicData.code" placeholder="请输入" autocomplete="off" />
              </el-form-item>
            </el-col>
            <el-col :sm="12" :lg="6">
              <el-form-item label="别名" prop="name">
                <el-input v-model="basicData.name" placeholder="请输入" autocomplete="off" />
              </el-form-item>
            </el-col>
            <el-col :sm="12" :lg="6" v-if="basicData.type == BSDataTypeEnum.Class">
              <el-form-item label="参数连接符" prop="separator">
                <el-input v-model="basicData.separator" placeholder="请输入" autocomplete="off" />
              </el-form-item>
            </el-col>
            <el-col :sm="12" :lg="6">
              <el-form-item label="标签" prop="tag">
                <SelectTag module="basicData" v-model:task_tags="basicData.tag" :max-collapse-tags="2" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :sm="12" :lg="6" v-if="basicData.type == BSDataTypeEnum.Class">
              <el-form-item label="父类" prop="parentId">
                <el-select v-model="basicData.parentId" filterable placeholder="请选择" style="width: 100%">
                  <el-option
                    v-for="item in parentOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :sm="12" :lg="12">
              <el-form-item label="描述">
                <el-input v-model="basicData.description" type="textarea" show-word-limit placeholder="请输入" autocomplete="off" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="cpi-header">
        <span class="cpi-header-text">参数集</span>
        <span class="cpi-header-text-right">
          <span class="cpi-header-text-right-text" @click="activeTab = 'table'" :class="{ active: activeTab === 'table' }">表格</span>
          <span class="cpi-header-text-right-text" @click="activeTab = 'topology'" :class="{ active: activeTab === 'topology' }">拓扑</span>
        </span>
      </div>
      <div class="cpi-content" v-show="activeTab === 'table'">
        <div class="cpi-content-toolbar mb-3">
          <el-space>
            <el-button type="primary" @click="handleCreateTask()">
              新建参数
            </el-button>
            <el-button :disabled="!deleteBtn" type="danger" @click="handleMultipleDelete">
              批量删除
            </el-button>
          </el-space>
        </div>
        <div class="cpi-content-main" v-if="basicData.type === BSDataTypeEnum.Class">
          <vxe-table class="cpi-table" ref="fieldTableRef" height="auto" show-overflow highlight-hover-row show-header auto-resize keep-source size="small" :edit-rules="validRules" :data="tableData" :mouse-config="{ selected: false }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" :row-config="{ drag: true, useKey: true }" :row-drag-config="{ trigger: 'cell', showGuidesStatus: false }" :align="'left'" header-align="left">
            <vxe-table-column type="checkbox" width="40" />
            <vxe-table-column type="seq" title="序号" align="center" header-align="center" width="60" drag-sort />
            <vxe-table-column field="code" title="参数名">
              <template #default="{ row }">
                <el-input v-model="row.code" />
              </template>
            </vxe-table-column>
            <vxe-table-column field="name" title="参数描述">
              <template #default="{ row }">
                <el-input v-model="row.name" />
              </template>
            </vxe-table-column>
            <vxe-table-column field="type" title="分类" formatter="formatType" />
            <vxe-table-column field="separator" title="参数连接符" />
            <vxe-table-column field="typeCode" title="数据类型" :cell-render="{ name: 'EditDownModal' }" />
          </vxe-table>
        </div>
        <div class="cpi-content-main" v-if="basicData.type === BSDataTypeEnum.Enum">
          <vxe-table class="cpi-table" ref="fieldTableRef" height="auto" show-overflow highlight-hover-row show-header auto-resize keep-source size="small" :edit-rules="validEnumRules" :data="tableData" :mouse-config="{ selected: false }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" :row-config="{ drag: true, useKey: true }" :row-drag-config="{ trigger: 'cell', showGuidesStatus: false }" :align="'left'" header-align="left">
            <vxe-table-column type="checkbox" width="40" />
            <vxe-table-column type="seq" title="序号" align="center" header-align="center" width="60" drag-sort />
            <vxe-table-column field="value" title="枚举名称">
              <template #default="{ row }">
                <el-input v-model="row.name" />
              </template>
            </vxe-table-column>
            <vxe-table-column field="code" title="枚举值">
              <template #default="{ row }">
                <el-input v-model="row.code" />
              </template>
            </vxe-table-column>
            <vxe-table-column field="comment" title="注释">
              <template #default="{ row }">
                <el-input v-model="row.comment" />
              </template>
            </vxe-table-column>
          </vxe-table>
        </div>
      </div>
      <div class="cpi-content" v-if="activeTab === 'topology'">
        <componentVue :is-enum="basicData.type == BSDataTypeEnum.Enum" :handle-create-task="handleTopCreateTask" :father-data="tableData" :admin-user="basicData.code" :list-obj="listObj" :handle-remove-node="removeNode" :handle-edit="handleEditDialog" />
      </div>
    </div>
    <basicDrawer v-if="basicData.type === BSDataTypeEnum.Class" ref="basicDrawerRef" :visible="dialogVisible" :static-flag="1" :default-info="editParamValue" :dialog-type="dialogTyle" @close-dialog="closeDialog" @handle-confirm="handleConfirm" />

    <EnumDrawer v-if="basicData.type === BSDataTypeEnum.Enum" ref="basicDrawerRef" :dialog-type="dialogTyle" :visible="dialogVisible" :default-info="editParamValue" @close-dialog="closeDialog" @handle-confirm="handleConfirm" />

    <div class="pager-wrapper center">
      <el-button type="primary" @click="handleSave">
        保存
      </el-button>
      <el-button @click="handleCancel">
        退出
      </el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import "@@/assets/styles/mixins.scss";

.app-container-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 10px;
  @extend %scrollbar;
}

.cpi-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}
</style>
